import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'
import { routes, roleNameList } from '@/router/routerMap'

const storeSetup = () => {
  const userStore = useUserStore()
  /* 定义数据--------------------------------------------------------------------- */

  // 菜单列表
  const menuList = ref([])

  // 当前菜单sort
  const currentMenuSort = ref('1')

  // 权限菜单列表
  const roleMenuList = ref([])

  // tabs标签页列表
  const tabsList = ref([
    {
      title: '工作台',
      path: '/home',
      name: 'Home',
      sort: '1',
    },
  ])

  /* 定义函数--------------------------------------------------------------------- */

  // 设置权限菜单列表的函数
  const setRoleMenuListFunc = () => {
    let roleMenus = []

    let roleNl = roleNameList.filter((rnl) => {
      return rnl.role == userStore.currentUserRole
    })[0].roleNames

    roleMenus = routes[1].children.filter((routeItem) => {
      return roleNl.indexOf(routeItem.name) != -1
    })
    console.log('roleMenus', roleMenus)
    menuList.value = roleMenus
    let roleMenusStr = JSON.stringify(roleMenus)

    localStorage.setItem('roleMenus', roleMenusStr)
    localStorage.setItem('currentUserRole', userStore.currentUserRole)
  }

  // 增加标签
  const addTab = (tab) => {
    tabsList.value.push(tab)
  }

  // 删除某个标签
  const deleteTab = (name) => {
    tabsList.value = tabsList.value.filter((tab) => {
      return tab.name != name
    })
  }

  // 清除所有标签
  const clearAllTab = () => {
    tabsList.value = []
  }

  // 返回参数
  return {
    currentMenuSort,
    tabsList,
    menuList,
    addTab,
    deleteTab,
    clearAllTab,
    setRoleMenuListFunc,
  }
}

// 导出Store
export const useRouterStore = defineStore('router', storeSetup, {
  persist: true,
})
